/**
 *
 */
package idao.support.spring;

import idao.IDAO;
import idao.IDAOFactory;
import idao.support.Dao;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.core.Ordered;

/**
 * Together with annotation {@link Dao} to provide support for annotation based
 * automatic bean configuration introduced in Spring2.
 * This post processor will take over instantication for all beans
 * that are annotated with {@link Dao}, except if it is not an interface.
 * Generally speaking, maybe this processor should be executed before those
 * proxy auto creator and the like post processors.
 * 
 * @author huhao
 */
public class DaoBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements
                Ordered
{

    private int order = Ordered.LOWEST_PRECEDENCE - 1;
    private IDAO iDao;

    public DaoBeanPostProcessor(DataSource ds)
    {
        this.iDao = IDAOFactory.newIDAO(new SpringAwareConnectionManager(ds));
    }

    @Override
    @SuppressWarnings("unchecked")
    public Class predictBeanType(Class beanClass, String beanName)
    {
        return beanClass;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Object postProcessBeforeInstantiation(Class beanClass, String beanName)
                    throws BeansException
    {
        if (beanClass.isInterface() && beanClass.isAnnotationPresent(Dao.class)) {
            return iDao.newDao(beanClass);
        }
        return super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    public int getOrder()
    {
        return order;
    }

    public void setOrder(int order)
    {
        this.order = order;
    }
}
